package org.sky.action;

import com.opensymphony.xwork2.ModelDriven;
import org.apache.log4j.Logger;
import org.sky.base.PageView;
import org.sky.model.Authority;
import org.sky.model.Booking;
import org.sky.model.Person;
import org.sky.model.State;
import org.sky.service.BookingService;
import org.sky.service.PersonService;
import org.sky.util.ChangeTime;
import org.sky.vo.BookingVO;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-11-30
 * Time: 下午6:21
 * To change this template use File | Settings | File Templates.
 */

@Component("order")
@Scope("prototype")
public class OrderAction extends MyActionSupport implements ModelDriven<BookingVO> {

    private final BookingVO bookingVO = new BookingVO();
    private BookingService bookingService;
    private PersonService personService;
    private Booking booking = new Booking();
    private List<Booking> bookings = new ArrayList<Booking>();

    UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    private final String username = userDetails.getUsername();
    String authority = userDetails.getAuthorities().iterator().next().getAuthority();

    private final static Logger logger = Logger.getLogger(OrderAction.class);

    //添加订单
    @Override
    public String execute() {
        Person p = personService.findPersonByUserName(username);
        if (p.isEnabled() && p.getCredit() < 60) {
            bookingVO.setResultMessage("<script>alert('当前用户信誉度过低！预约失败！请与工作人员联系！');location.href='/page/order/AddOrder.jsp';</script>");
            return ERROR;
        }

        if ("".equals(bookingVO.getBeginTime()) || "".equals(bookingVO.getEndTime()) || "".equals(bookingVO.getName()) || "".equals(bookingVO.getTel()) || "".equals(bookingVO.getSingerNum())) {
            bookingVO.setResultMessage("<script>alert('填写信息不完整！请重新填写！');location.href='/page/order/AddOrder.jsp';</script>");
            return ERROR;
        }

        if (setDate(bookingVO.getBeginTime()).getTime() >= setDate(bookingVO.getEndTime()).getTime()) {
            bookingVO.setResultMessage("<script>alert('结束时间必须比开始时间晚！请重新填写！');location.href='/page/order/AddOrder.jsp';</script>");
            return ERROR;
        }

        if (bookingService.findBookingByBeginDate(setDate(bookingVO.getBeginTime()), setDate(bookingVO.getEndTime()), bookingVO.getName(), personService.findPersonByUserName(username))) {
            bookingVO.setResultMessage("<script>alert('请勿重复预约！');location.href='/page/order/AddOrder.jsp';</script>");
//            bookingVO.setResultMessage(bookingVO.getName() + "先生/小姐，您在" + new ChangeTime().formatWholeDate(setDate(bookingVO.getBeginTime())) + "--" + new ChangeTime().formatWholeDate(setDate(bookingVO.getEndTime())) + "时间段内已经预约！请重新选择时间!");
            return ERROR;
        }
        booking = this.copyDefaultMealInfo(booking, bookingVO);
        try {
            bookingService.save(booking);
        } catch (Exception e) {
            bookingVO.setResultMessage("<script>alert('预约失败！请查明原因后重新预约！');location.href='/page/order/AddOrder.jsp';</script>");
            logger.error(e);
            return ERROR;
        }
        //TODO:发邮件
        bookingVO.setResultMessage("<script>alert('预约成功！您的订单号为：" + bookingVO.getOrderId() + "！请妥善保管！请带上订单号按照预约时间达到本店！谢谢你的支持！');location.href='/page/order/AddOrder.jsp';</script>");
        //  bookingVO.setResultMessage("预约成功！您的订单号为：" + bookingVO.getOrderId() + "！请妥善保管！请带上订单号按照预约时间达到本店！谢谢你的支持！~");
        logger.trace("User:" + username + " booking.OrderId:" + booking.getOrderId());
        return SUCCESS;
    }

    //查看未审核订单
    public String findNotAuditOrder() {
        bookings = bookingService.findNotAuditOrder();
        if (bookings.size() <= 0) {
            bookingVO.setResultMessage("<script>alert('没有未审批的预约！');location.href='/index.jsp';</script>");
            return ERROR;
        }
        /** 每页显示的结果数 **/
        int maxResult = 4;
        /** 封装的页面数据 **/
        PageView<Booking> pageView = new PageView<Booking>(maxResult,
                bookingVO.getPage());
        int firstIndex = ((pageView.getCurrentPage() - 1) * pageView
                .getMaxResult());// 开始索引
        // 按照条件排序
        LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
        orderBy.put("id", "desc");

        State[] states = new State[1];
        states[0] = State.NOT_AUDIT;

        pageView.setQueryResult(bookingService.getScrollData(Booking.class, firstIndex, maxResult, "o.state=?", states, orderBy));
        bookingVO.setPageView(pageView);
        view = "/page/order/NotAuditOrder.jsp";
        return VIEW;
    }

    //查找订单
    public String findOrder() {
        if (bookingVO.getFlag() == 5) {
            if (bookingVO.getMessage().trim().isEmpty()) {
                bookingVO.setResultMessage("<script>alert('请输入相关信息！');location.href='/page/order/findOrder.jsp';</script>");
                return ERROR;
            }
            Person p = personService.findPersonByUserName(username);
            bookings = bookingService.findBookingByMeg(bookingVO.getMessage(), p.getId());
            if (bookings.size() > 0) {
                bookingVO.setOrders(bookings);
                view = "/page/order/findOrder.jsp";
                return VIEW;
            } else {
                bookingVO.setResultMessage("<script>alert('找不到预约！');location.href='/page/order/findOrder.jsp';</script>");
                return ERROR;
            }

        }
        booking = bookingService.findOrderByOrderId(bookingVO.getOrderId());
        if (booking == null) {
            bookingVO.setResultMessage("<script>alert('该预约不存在！');location.href='/page/order/NotAuditOrder.jsp';</script>");
            return ERROR;
        }

        if (Authority.ROLE_USER.toString().equals(authority) && !username.equals(booking.getUserId().getUserName())) {
            bookingVO.setResultMessage("<script>alert('您没有限权查看该订单！');location.href='/page/order/NotAuditOrder.jsp';</script>");
            return ERROR;
        }

        bookingVO.setOrder(booking);
        if (bookingVO.getFlag() == 1)
            view = "/page/order/CancelOrder.jsp";
        else
            view = "/page/order/AuditOrder.jsp";
        return VIEW;
    }

    //审核订单
    public String auditOrder() {
        if (bookingVO.getFlag() == 1) {
            bookings = bookingService.findNotAuditOrder();
            for (Booking b : bookings) {
                b.setState(State.AUDIT);
                b.setChargeMan(username);
                bookingService.update(b);
            }
            bookingVO.setResultMessage("<script>alert('审核成功！');location.href='/page/order/AuditOrder.jsp';</script>");
            //bookingVO.setResultMessage("审核成功");
            logger.trace("User:" + username + "audit all order");
            return SUCCESS;
        }

        booking = bookingService.findOrderByOrderId(bookingVO.getOrderId());
        if (booking == null) {
            bookingVO.setResultMessage("<script>alert('不存在该预约！');location.href='/page/order/AuditOrder.jsp';</script>");
            // bookingVO.setResultMessage("订单号为" + bookingVO.getOrderId() + "的订单不存在!");
            return ERROR;
        }
        booking.setState(State.AUDIT);
        booking.setChargeMan(username);
        bookingService.update(booking);
        bookingVO.setResultMessage("<script>alert('审核成功！');location.href='/page/order/AuditOrder.jsp';</script>");
        // bookingVO.setResultMessage("审核成功");
        logger.trace("User:" + username + "audit order(" + booking.getOrderId() + ")");
        return SUCCESS;
    }

    // 取消订单
    public String cancelOrder() {
        booking = bookingService.findOrderByOrderId(bookingVO.getOrderId());

        if (booking == null) {
            bookingVO.setResultMessage("<script>alert('订单不存在！');location.href='/page/order/CancelOrder.jsp';</script>");
            //bookingVO.setResultMessage("订单不存在!");
            return ERROR;
        }
        if (booking.getState().getState() == 1 && Authority.ROLE_USER.toString().equals(authority)) {

            bookingVO.setResultMessage("订单号为" + bookingVO.getOrderId() + "的订单已审核！~请与工作人员联系！");
            return ERROR;
        }

        if (!Authority.ROLE_ADMIN.toString().equals(authority)) {
            if (!username.equals(booking.getUserId().getUserName())) {
                bookingVO.setResultMessage("<script>alert('无法找到改订单！');location.href='/page/order/CancelOrder.jsp';</script>");
                //bookingVO.setResultMessage("订单号为" + bookingVO.getOrderId() + "的订单并不是你预定的！");
                return ERROR;
            }
        }

        booking.setState(State.CANCEL);
        booking.setCancelOrderTime(new ChangeTime().parseDate(new ChangeTime().getCurrentShortDate()));
        System.out.println(booking.getCancelOrderTime());
        bookingService.update(booking);
        bookingVO.setResultMessage("<script>alert('订单取消成功！');location.href='/page/order/CancelOrder.jsp';</script>");
        //bookingVO.setResultMessage("订单 " + bookingVO.getOrderId() + " 取消成功");
        logger.trace("User:" + username + "cancel order(" + booking.getOrderId() + ")");
        return SUCCESS;
    }

    @Override
    public BookingVO getModel() {
        return bookingVO;
    }

    @Resource(name = "bookingServiceImpl")
    public void setBookingService(BookingService bookingService) {
        this.bookingService = bookingService;
    }

    @Resource(name = "personServiceImpl")
    public void setPersonService(PersonService personService) {
        this.personService = personService;
    }

    private Booking copyDefaultMealInfo(Booking targetOrder, BookingVO bookingVO) {
        ChangeTime ct = new ChangeTime();
        targetOrder.setAddress(bookingVO.getAddress());
        targetOrder.setBeginTime(setDate(bookingVO.getBeginTime()));
        targetOrder.setEndTime(setDate(bookingVO.getEndTime()));
        targetOrder.setName(bookingVO.getName());
        targetOrder.setSingerNum(bookingVO.getSingerNum());
        targetOrder.setTel(bookingVO.getTel());
        targetOrder.setUserId(personService.findPersonByUserName(username));
        targetOrder.setOrderId(ct.getMd());
        bookingVO.setOrderId(ct.getMd());
        targetOrder.setCreateDate(ct.parseDate(targetOrder.getOrderId()));
        return targetOrder;
    }

    private Date setDate(String time) {
        return ChangeTime.parseDate(time + ":00");
    }
}
